#include "market_data_simulator.h"
#include "logger.h"
#include <chrono>
#include <thread>
#include <algorithm>

namespace yquote {

MarketDataSimulator::MarketDataSimulator()
    : running_(false), update_interval_ms_(1000), volatility_percent_(2.0),
      gen_(rd_()), price_dist_(-1.0, 1.0), volume_dist_(1000, 10000) {
    initializeDefaultSymbols();
}

MarketDataSimulator::~MarketDataSimulator() {
    stop();
}

void MarketDataSimulator::start() {
    if (running_.load()) {
        LOG_WARN("市场数据模拟器已经在运行中");
        return; // 已经在运行
    }
    
    running_.store(true);
    simulator_thread_ = std::thread(&MarketDataSimulator::simulatorLoop, this);
    
    LOG_INFO_FMT("市场数据模拟器已启动，更新间隔: %d ms", update_interval_ms_);
}

void MarketDataSimulator::stop() {
    if (!running_.load()) {
        return; // 已经停止
    }
    
    running_.store(false);
    
    if (simulator_thread_.joinable()) {
        simulator_thread_.join();
    }
    
    LOG_INFO("市场数据模拟器已停止");
}

bool MarketDataSimulator::isRunning() const {
    return running_.load();
}

void MarketDataSimulator::setDataCallback(DataCallback callback) {
    data_callback_ = std::move(callback);
    LOG_DEBUG("设置数据回调函数");
}

void MarketDataSimulator::addSymbol(const std::string& symbol, double initial_price) {
    // 检查是否已存在
    auto it = std::find_if(symbols_.begin(), symbols_.end(),
        [&symbol](const SymbolData& data) { return data.symbol == symbol; });
    
    if (it == symbols_.end()) {
        symbols_.emplace_back(symbol, initial_price);
        LOG_INFO_FMT("添加股票: %s, 初始价格: %.2f", symbol.c_str(), initial_price);
    } else {
        LOG_DEBUG_FMT("股票 %s 已存在，跳过添加", symbol.c_str());
    }
}

void MarketDataSimulator::removeSymbol(const std::string& symbol) {
    auto original_size = symbols_.size();
    symbols_.erase(
        std::remove_if(symbols_.begin(), symbols_.end(),
            [&symbol](const SymbolData& data) { return data.symbol == symbol; }),
        symbols_.end());
    
    if (symbols_.size() < original_size) {
        LOG_INFO_FMT("移除股票: %s", symbol.c_str());
    } else {
        LOG_WARN_FMT("尝试移除不存在的股票: %s", symbol.c_str());
    }
}

void MarketDataSimulator::setUpdateInterval(int interval_ms) {
    int old_interval = update_interval_ms_;
    update_interval_ms_ = std::max(100, interval_ms); // 最小100ms
    
    if (update_interval_ms_ != interval_ms) {
        LOG_WARN_FMT("更新间隔调整为最小值: %d ms (请求值: %d ms)", update_interval_ms_, interval_ms);
    } else if (old_interval != update_interval_ms_) {
        LOG_INFO_FMT("更新间隔设置为: %d ms", update_interval_ms_);
    }
}

void MarketDataSimulator::setPriceVolatility(double volatility_percent) {
    double old_volatility = volatility_percent_;
    volatility_percent_ = std::max(0.1, std::min(10.0, volatility_percent)); // 限制在0.1%-10%
    
    if (volatility_percent_ != volatility_percent) {
        LOG_WARN_FMT("价格波动率调整为: %.2f%% (请求值: %.2f%%, 范围: 0.1%%-10%%)", 
                     volatility_percent_, volatility_percent);
    } else if (old_volatility != volatility_percent_) {
        LOG_INFO_FMT("价格波动率设置为: %.2f%%", volatility_percent_);
    }
}

void MarketDataSimulator::simulatorLoop() {
    LOG_DEBUG("市场数据模拟器循环开始");
    
    while (running_.load()) {
        auto start_time = std::chrono::steady_clock::now();
        
        // 为每个股票生成新的行情数据
        for (auto& symbol_data : symbols_) {
            double new_price = generateNextPrice(symbol_data);
            long long new_volume = generateVolume();
            
            // 更新统计数据
            symbol_data.current_price = new_price;
            symbol_data.high_price = std::max(symbol_data.high_price, new_price);
            symbol_data.low_price = std::min(symbol_data.low_price, new_price);
            symbol_data.volume += new_volume;
            
            // 创建QuoteData对象
            QuoteData quote;
            quote.symbol = symbol_data.symbol;
            quote.price = new_price;
            quote.open = symbol_data.open_price;
            quote.high = symbol_data.high_price;
            quote.low = symbol_data.low_price;
            quote.close = new_price; // 当前价格作为收盘价
            quote.volume = new_volume;
            quote.timestamp = std::chrono::system_clock::now();
            
            // 计算涨跌额和涨跌幅
            if (symbol_data.open_price > 0) {
                quote.change = new_price - symbol_data.open_price;
                quote.change_percent = (quote.change / symbol_data.open_price) * 100.0;
            }
            
            // 调用回调函数
            if (data_callback_) {
                data_callback_(quote);
            }
            
            LOG_TRACE_FMT("生成 %s 行情: 价格=%.2f, 涨跌=%.2f(%.2f%%), 成交量=%lld", 
                         quote.symbol.c_str(), quote.price, quote.change, quote.change_percent, quote.volume);
        }
        
        // 计算睡眠时间
        auto end_time = std::chrono::steady_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
        auto sleep_time = std::chrono::milliseconds(update_interval_ms_) - elapsed;
        
        if (sleep_time > std::chrono::milliseconds(0)) {
            std::this_thread::sleep_for(sleep_time);
        } else {
            LOG_WARN_FMT("行情生成耗时 %lld ms 超过更新间隔 %d ms", elapsed.count(), update_interval_ms_);
        }
    }
    
    LOG_DEBUG("市场数据模拟器循环结束");
}

double MarketDataSimulator::generateNextPrice(SymbolData& symbol_data) {
    // 生成随机价格变化
    double change_percent = price_dist_(gen_) * volatility_percent_ / 100.0;
    double new_price = symbol_data.current_price * (1.0 + change_percent);
    
    // 确保价格不会变成负数或过小
    new_price = std::max(new_price, symbol_data.base_price * 0.1);
    
    // 添加一些趋势性（让价格有一定的连续性）
    static thread_local double trend = 0.0;
    trend = trend * 0.9 + change_percent * 0.1; // 平滑趋势
    
    return new_price;
}

long long MarketDataSimulator::generateVolume() {
    return volume_dist_(gen_);
}

void MarketDataSimulator::initializeDefaultSymbols() {
    LOG_DEBUG("初始化默认股票列表");
    
    // 添加一些默认的股票
    addSymbol("AAPL", 150.25);
    addSymbol("GOOGL", 2800.50);
    addSymbol("MSFT", 330.75);
    addSymbol("AMZN", 3200.00);
    addSymbol("TSLA", 800.25);
    addSymbol("META", 320.50);
    addSymbol("NVDA", 450.75);
    addSymbol("NFLX", 380.25);
    
    // 中国股票
    addSymbol("000001.SZ", 15.80); // 平安银行
    addSymbol("000002.SZ", 25.60); // 万科A
    addSymbol("600000.SH", 8.90);  // 浦发银行
    addSymbol("600036.SH", 35.20); // 招商银行
    
    LOG_INFO_FMT("默认股票列表初始化完成，共 %zu 只股票", symbols_.size());
}

} // namespace yquote 